package com.jhs.kjs.controller;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.jhs.kjs.dto.CustomerUserDTO;
import com.jhs.kjs.dto.UserDTO;
import com.jhs.kjs.handler.SpamPreventHandler;
import com.jhs.kjs.handler.exception.AldangMessegeException;
import com.jhs.kjs.model.UserModel;
import com.jhs.kjs.service.IUserService;

@Controller
@RequestMapping(value = "/user")
@SessionAttributes("userSessionInfo")
public class UserController extends CommonController {
	private static final Logger logger = LoggerFactory
			.getLogger(UserController.class);
	@Autowired
	IUserService userService;

	@Resource(name = "authenticationManager")
	@Qualifier("authenticationManager")
	private AuthenticationManager authenticationManager; // specific for Spring
															// Security

	@RequestMapping(value = "/join1", method = { RequestMethod.GET,
			RequestMethod.POST })
	public ModelAndView join1(Model model, HttpServletRequest request,
			CustomerUserDTO customerUserDTO) {
		
		ModelAndView mav = new ModelAndView();
		mav.addObject("menuList", getUserBoardList());
		mav.setViewName("user/join1");
		return mav;
	}

	@RequestMapping(value = "/join2", method = { RequestMethod.POST })
	public ModelAndView join2(HttpServletRequest request,
			@RequestParam Map<String, String> param) {

		String viewName = "user/join1";
		ModelAndView mav = new ModelAndView();
		if (StringUtils.equals("true", param.get("agreed1"))
				&& StringUtils.equals("true", param.get("agreed1"))) {
			viewName = "user/join2";
		}
		SpamPreventHandler.INSTANCE.addSpamFree(request, mav);
		mav.addObject("menuList", getUserBoardList());
		mav.setViewName(viewName);
		return mav;
	}

	@RequestMapping(value = "/join2", method = { RequestMethod.GET })
	public ModelAndView join2Redirect(@RequestParam Map<String, String> param) {
		String viewName = "/home";
		return new ModelAndView(viewName);
	}

	@RequestMapping(value = "/join3", method = { RequestMethod.POST })
	public ModelAndView join3(HttpServletResponse response,
			HttpServletRequest request, @ModelAttribute("userForm") UserDTO user) {
		ModelAndView mav = new ModelAndView();
		String viewName = "user/join3";
		UserModel userModel = new UserModel(userService);

		try {
			SpamPreventHandler.INSTANCE.checkSpamFree(request, user);
			userModel.insertValidateUser(user);
			userService.addNewUser(user);
			mav.addObject("user", user);
		} catch (Exception e) {
			e.getMessage();
			viewName = "/user/join2";
			mav.addObject("msg", e.getMessage());
			SpamPreventHandler.INSTANCE.addSpamFree(request, mav);
		}
		mav.addObject("menuList", getUserBoardList());
		mav.setViewName(viewName);

		return mav;
	}

	@RequestMapping(value = "/reloadSpamFilter", method = { RequestMethod.POST })
	public String reloadSpamFilter(HttpServletRequest request, Model model) {
		SpamPreventHandler.INSTANCE.addSpamFree(request, model);

		return "";

	}

	@RequestMapping(value = "/loginFail", method = { RequestMethod.GET,
			RequestMethod.POST })
	public String loginFail(Model model, HttpServletRequest request,
			UserDTO userDTO) {
		HttpSession session = request.getSession(true);
		try {
			String userId = session.getAttribute("j_username").toString();
			if (userId != null && !"".equals(userId)) {
				userService.updatePwFailCnt(userId);
			}
			session.setAttribute("j_username", null);
		} catch (Exception e) {
		}
		
		model.addAttribute("msg", "true");
		return "redirect:/signin";
	}

	@RequestMapping(value = "/memberUpdate", method = { RequestMethod.POST })
	public ModelAndView memberUpdate(HttpServletResponse response,
			HttpServletRequest request, @ModelAttribute("userForm") UserDTO user) {
		ModelAndView mav = new ModelAndView();
		String viewName = "redirect:/mypage";
		UserModel userModel = new UserModel(userService);

		try {
			SpamPreventHandler.INSTANCE.checkSpamFree(request, user);
			userModel.validateUser(user);
			setUserIndex(request, user);
			userService.updateUser(user);
			mav.addObject("user", getUser(request, true));
			mav.addObject("msg", "success");
		} catch (AldangMessegeException e) {
			e.printStackTrace();
			String errorMsg = e.getMessage();
			viewName = memberUpdateErrorHandler(request, mav, errorMsg);
		} catch (Exception e) {
			e.printStackTrace();
			String errorMsg = "알수 없는 에러가 발생하였습니다. 관리자에게 문의해 주세요.";
			viewName = memberUpdateErrorHandler(request, mav, errorMsg);
		}
		mav.setViewName(viewName);

		return mav;
	}

	private void setUserIndex(HttpServletRequest request, UserDTO user) {

		HttpSession session = request.getSession();
		UserDTO sessionUser = (UserDTO) (session.getAttribute(UserModel.USER_SESSION_INFO));
				
		if (sessionUser.getUserIndex() == null || sessionUser.getUserIndex() < 1)
			throw new AldangMessegeException("세션이 끊어졌습니다. 다시 로그인해주세요.");
		user.setUserIndex(sessionUser.getUserIndex());
		user.setUserId(sessionUser.getUserId());
	}

	private String memberUpdateErrorHandler(HttpServletRequest request,
			ModelAndView mav, String errorMsg) {
		mav.addObject("msg", errorMsg);
		SpamPreventHandler.INSTANCE.addSpamFree(request, mav);
		return "/user/join2";
	}
}
